package bigoo.util;

import static java.util.logging.Logger.GLOBAL_LOGGER_NAME;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class Config {
    
    public final static String BIGOO_PROPERTIES = "bigoo.properties";
    public final static String DS_PROPERTIES = "ds.properties";
    
    // Properties keys and default values
    public static String LOG_LEVEL_PROP = "log.level";
    private static String LOG_LEVEL_DEFAULT = "FINEST";
    public static String LOG_FILE_PROP = "log.file";
    public static String DS_PORT = "ds.port";
    public static String DS_LEASE_TIME_PROP = "ds.leasetime";
    public static String DS_THRESHOLD_PROP = "ds.threshold";
    public static String PEER_DS_ADDRESS = "peer.ds.address";
    public static String PEER_DS_PORT = "peer.ds.port";
    public static String PEER_PORT = "peer.port";
    
    private static Properties props = null;
    
    public synchronized static Properties getProperties() {
	if ( props == null ) {
	    throw new IllegalStateException("Properties not load yet!");
	}
	return props;
    }

    public static void loadProperties(String filename) {
	try {
	    props = new Properties();
	    props.load(new FileInputStream(filename));
	} catch (IOException ioex) {
	    System.err.println("Properties file not found, ABORTING!!!");
	    System.exit(-1);
	}
    }
    
    public static void configureLog() throws SecurityException, IOException {
	getProperties();
	Logger logger = Logger.getLogger(GLOBAL_LOGGER_NAME);
	logger.setUseParentHandlers(false);
	
	Level level = Level.parse(props.getProperty(LOG_LEVEL_PROP, LOG_LEVEL_DEFAULT).toUpperCase());
	String logFile = props.getProperty(LOG_FILE_PROP);
	
	Handler handler = (logFile != null) ? new FileHandler(logFile, true) : new ConsoleHandler();
	handler.setFormatter(new SimpleFormatter());
	handler.setLevel(level);
	logger.setLevel(level);
	logger.addHandler(handler);
    }

}
